/**
 * @file key.c
 * @author morris (a_morris@163.com)
 * @brief
 * @version 0.1
 * @date 2022-03-10
 *
 * @copyright Copyright (c) 2022
 *
 */
#include "key.h"

#include "acommon_err.h"

void key_init(void)
{
  stc_gpio_cfg_t stcGpioCfg;

  Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);

  stcGpioCfg.enDir      = GpioDirIn;
  stcGpioCfg.enDrv      = GpioDrvL;
  stcGpioCfg.enPu       = GpioPuDisable;
  stcGpioCfg.enPd       = GpioPdDisable;
  stcGpioCfg.enOD       = GpioOdDisable;
  stcGpioCfg.enCtrlMode = GpioAHB;
  Gpio_Init(SW_1_IN_PORT, SW_1_IN_PIN, &stcGpioCfg);

  stcGpioCfg.enDir = GpioDirOut;
  stcGpioCfg.enPd  = GpioPdDisable;
  // stcGpioCfg.enPu  = GpioPuEnable;
  Gpio_Init(SW_1_PWR_PORT, SW_1_PWR_PIN, &stcGpioCfg);
  Gpio_SetIO(SW_1_PWR_PORT, SW_1_PWR_PIN);

  // ///< enable GPIO interrupt
  // Gpio_ClearIrq(SW_1_IN_PORT, SW_1_IN_PIN);
  // Gpio_EnableIrq(SW_1_IN_PORT, SW_1_IN_PIN, GpioIrqFalling);
  // EnableNvic(PORTA_IRQn, IrqLevel3, TRUE); // comm IrqLevel higher than RTC
}

void key_deinit(void)
{
  Gpio_ClrIO(SW_1_PWR_PORT, SW_1_PWR_PIN);

  stc_gpio_cfg_t stcGpioCfg;

  stcGpioCfg.enDir      = GpioDirIn;
  stcGpioCfg.enDrv      = GpioDrvL;
  stcGpioCfg.enPu       = GpioPuDisable;
  stcGpioCfg.enPd       = GpioPdEnable;
  stcGpioCfg.enOD       = GpioOdDisable;
  stcGpioCfg.enCtrlMode = GpioAHB;

  Gpio_Init(GpioPortA, GpioPin9, &stcGpioCfg);
}

int sw1_get_state(void)
{
  int            delay = 0xff;
  boolean_t      state = FALSE;
  stc_gpio_cfg_t stcGpioCfg;

  Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);

  stcGpioCfg.enDir      = GpioDirIn;
  stcGpioCfg.enDrv      = GpioDrvL;
  stcGpioCfg.enPu       = GpioPuDisable;
  stcGpioCfg.enPd       = GpioPdDisable;
  stcGpioCfg.enOD       = GpioOdDisable;
  stcGpioCfg.enCtrlMode = GpioAHB;
  Gpio_Init(SW_1_IN_PORT, SW_1_IN_PIN, &stcGpioCfg);

  stcGpioCfg.enDrv = GpioDrvL;
  stcGpioCfg.enDir = GpioDirOut;
  Gpio_Init(SW_1_PWR_PORT, SW_1_PWR_PIN, &stcGpioCfg);
  Gpio_SetIO(SW_1_PWR_PORT, SW_1_PWR_PIN);
  while (delay--)
    ;
  if (FALSE == Gpio_GetInputIO(SW_1_IN_PORT, SW_1_IN_PIN)) { state = TRUE; }
  else { state = FALSE; }
  Gpio_ClrIO(SW_1_PWR_PORT, SW_1_PWR_PIN);
  stcGpioCfg.enDrv = GpioDrvH;
  stcGpioCfg.enDir = GpioDirIn;
  stcGpioCfg.enPd  = GpioPdEnable;
  Gpio_Init(SW_1_PWR_PORT, SW_1_PWR_PIN, &stcGpioCfg);

  return state;
}
